<template>
    <div>
        <!--面包屑区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--卡片区域-->
        <el-card>
            <!--卡片区域-操作栏-->
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-input placeholder="请输入用户名" v-model.trim="queryInfo.query" clearable @clear="init">
                        <el-button slot="append" icon="el-icon-search" @click="init"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" icon="el-icon-s-custom" @click="addUserDialogFormVisible = true">添加用户
                    </el-button>
                </el-col>
            </el-row>
            <!--卡片区域-表格区域-->
            <el-table
                    border
                    v-loading="is_load"
                    :data="tableData"
                    stripe
                    style="width: 100%">
                <el-table-column align="center" type="index" label="序号" width="100">
                </el-table-column>
                <el-table-column align="center" prop="id" label="编号" width="180">
                </el-table-column>
                <el-table-column align="center" prop="role_name" label="身份" width="180">
                </el-table-column>
                <el-table-column align="center" prop="username" label="用户名">
                </el-table-column>
                <el-table-column align="center" prop="mobile" label="电话">
                </el-table-column>
                <el-table-column align="center" prop="email" label="邮箱">
                </el-table-column>
                <el-table-column align="center" label="状态">
                    <template slot-scope="scope">
                        <el-switch
                                @change="msState(scope.row)"
                                v-model="scope.row.mg_state"
                                inactive-color="#ff4949">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" style="margin-right: 10px" type="primary" icon="el-icon-edit"
                                   @click="getUserById(scope.row.id)">
                        </el-button>
                        <el-popconfirm
                                placement="top"
                                confirmButtonText='好的'
                                cancelButtonText='不用了'
                                @onConfirm="sureDelete(scope.row.id)"
                                icon="el-icon-info"
                                iconColor="red"
                                :title="`确定删除 【${scope.row.username}】 吗？`">
                            <el-button style="margin-right: 10px" size="mini" type="danger" slot="reference"
                                       icon="el-icon-delete">
                            </el-button>
                        </el-popconfirm>

                        <el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
                            <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRole(scope.row)">
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    :page-sizes="[3,5,10, 20]"
                    :page-size="queryInfo.pagesize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalCount">
            </el-pagination>
            <!--对话框标题-->
            <el-dialog title="添加用户"
                       :visible.sync="addUserDialogFormVisible"
                       width="35%"
                       @close="closeDialog('addUserForm')"
                       :close-on-click-modal="false">
                <!--对话框的按钮-->
                <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserForm" status-icon>
                    <el-form-item label="用户名:" prop="username" label-width="11%">
                        <el-input prefix-icon="el-icon-user" v-model="addUserForm.username" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="密　码:" prop="password" label-width="11%">
                        <el-input prefix-icon="el-icon-lock" v-model="addUserForm.password" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="邮　箱:" prop="email" label-width="11%">
                        <el-input prefix-icon="el-icon-message" v-model="addUserForm.email" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="手机号:" prop="mobile" label-width="11%">
                        <el-input prefix-icon="el-icon-phone-outline" maxlength="11" v-model="addUserForm.mobile"
                                  clearable></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="addUserDialogFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="addUser">确 定</el-button>
                    </div>
                </template>
            </el-dialog>
            <!--修改用户对话框-->
            <el-dialog title="修改用户"
                       :visible.sync="updateUserDialogFormVisible"
                       width="35%"
                       @close="closeDialog('updateUserForm')"
                       :close-on-click-modal="false">
                <!--对话框的按钮-->
                <el-form :model="updateUserFrom" :rules="updateUserFromRules" ref="updateUserForm" status-icon>
                    <el-form-item label="用户名:" prop="username" label-width="11%">
                        <el-input prefix-icon="el-icon-user" v-model="updateUserFrom.username" disabled
                                  clearable></el-input>
                    </el-form-item>
                    <el-form-item label="邮　箱:" prop="email" label-width="11%">
                        <el-input prefix-icon="el-icon-message" v-model="updateUserFrom.email" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="手机号:" prop="mobile" label-width="11%">
                        <el-input prefix-icon="el-icon-phone-outline" maxlength="11" v-model="updateUserFrom.mobile"
                                  clearable></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="updateUserDialogFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="updateUser">确 定</el-button>
                    </div>
                </template>
            </el-dialog>
            <!--分配角色对话框-->
            <el-dialog
                    title="分配角色"
                    :visible.sync="setRoleDialog"
                    width="30%">
                <div>
                    <p>当前用户：<span style="color: red">{{userRole.username}}</span></p>
                    <p>当前角色：<span style="color: red">{{userRole.role_name}}</span></p>
                    <p>分配角色：
                        <template>
                            <!--回显用户角色信息，选择option后，会把对应的value值赋给v-model-->
                            <el-select v-model="selectedRoleId" placeholder="请选择" :loading="is_load">
                                <el-option
                                        v-for="item in userRoleList"
                                        :key="item.id"
                                        :label="item.roleName"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </template>
                    </p>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="setRoleDialog = false">取 消</el-button>
                    <el-button type="primary" @click="updateUserRole">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>

    </div>
</template>

<script>
    import $axios from "../../network/request";

    export default {
        name: "Users",
        data() {
            //from表单邮箱验证
            const checkEmail = (rules, value, callback) => {
                const emailCheck = '^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$'
                if (value.match(emailCheck)) {
                    callback()
                }
                callback(new Error("请输入正确的邮箱"))
            }
            //form表单手机号验证
            const checkMobile = (rules, value, callback) => {
                const mobileCheck = /^1[3456789]\d{9}$/
                if (mobileCheck.test(value)) {
                    callback()
                }
                callback(new Error("请输入正确的手机号"))
            }

            return {
                queryInfo: {
                    query: '',
                    pagenum: 1,
                    pagesize: 10
                },
                tableData: [],
                totalCount: 0,
                //控制对话框的显示隐藏
                addUserDialogFormVisible: false,
                updateUserDialogFormVisible: false,
                //绑定addUserform表单数据
                addUserForm: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''
                },
                //绑定addUserfrom表单规则
                addUserFormRules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 5, max: 16, message: '长度在 5 到 16 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 5, max: 16, message: '长度在 5 到 16 个字符', trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'},
                        {min: 5, max: 16, message: '长度在 5 到 16 个字符', trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '请输入手机号码', trigger: 'blur'},
                        {validator: checkMobile, trigger: 'blur'},
                    ]
                },
                //绑定修改表单的数据
                updateUserFrom: {},
                //绑定修改表单的规则
                updateUserFromRules: {
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'},
                        {min: 5, max: 16, message: '长度在 5 到 16 个字符', trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '请输入手机号码', trigger: 'blur'},
                        {validator: checkMobile, trigger: 'blur'},
                    ]
                },
                //分配角色对话框
                setRoleDialog: false,
                userRole: {},
                userRoleList: {},
                //选中的角色ID
                selectedRoleId: {},
            }
        },
        methods: {
            //数据初始化
            init() {
                $axios({
                    url: '/users',
                    method: 'get',
                    params: this.queryInfo
                }).then(res => {
                    if (res.data.meta.status !== 200) {
                        this.$message.error("数据请求异常")
                    } else {
                        this.totalCount = res.data.data.total
                        this.tableData = res.data.data.users
                    }
                })
            },
            //监听newPageSize
            handleSizeChange(newPageSize) {
                this.queryInfo.pagesize = newPageSize;
                this.init();
            },
            //监听翻页
            handleCurrentChange(newPageNum) {
                this.queryInfo.pagenum = newPageNum;
                this.init()
            },
            //监听用户状态修改事件
            msState(newState) {
                $axios({
                    method: 'put',
                    url: `users/${newState.id}/state/${newState.mg_state}`
                }).then(res => {
                        if (res.data.meta.status !== 200) {
                            newState.mg_state = !newState.mg_state
                            this.$message.error(`${newState.username} -> 状态修改失败，请重试`)
                        } else {
                            this.$message.success(`${newState.username} -> 状态修改成功`)
                        }
                    }
                )
            },
            //监听弹窗关闭的时间
            closeDialog(name) {
                //弹窗关闭前重置弹窗
                this.$refs[name].resetFields();
            },
            // 监听弹窗确认按钮事件
            addUser() {
                //确认弹窗之前验证规则
                this.$refs.addUserForm.validate(valid => {
                    if (valid) {
                        $axios({
                            method: 'post',
                            url: '/users',
                            data: {
                                username: this.addUserForm.username,
                                password: this.addUserForm.password,
                                email: this.addUserForm.email,
                                mobile: this.addUserForm.mobile
                            }
                        }).then(res => {
                            if (res.data.meta.status !== 201) {
                                this.$message.error("添加失败")
                            } else {
                                this.addUserDialogFormVisible = false
                                this.$message.success("添加成功")
                                //添加成功之后刷新列表
                                this.init()
                            }
                        })
                    }
                })
            },
            //用户修改之前先获取id,回填数据
            getUserById(id) {
                $axios({
                    method: 'get',
                    url: `users/${id}`,
                }).then(res => {
                    if (res.data.meta.status !== 200) {
                        this.$message('获取用户失败')
                    } else {
                        this.updateUserDialogFormVisible = true
                        //回填用户数据
                        this.updateUserFrom = res.data.data
                    }
                })
            },
            //修改用户数据
            updateUser() {
                this.$refs.updateUserForm.validate(valid => {
                    if (valid) {
                        $axios({
                            method: 'put',
                            url: `users/${this.updateUserFrom.id}`,
                            data: {
                                email: this.updateUserFrom.email,
                                mobile: this.updateUserFrom.mobile
                            }
                        }).then(res => {
                            if (!res.data.meta) {
                                this.$message.error("用户修改失败")
                            } else {
                                this.updateUserDialogFormVisible = false
                                this.$message.success(`${res.data.data.username} -> 修改成功`)
                                this.init()
                            }
                        })
                    }
                    return
                })
            },
            sureDelete(userId) {
                $axios({
                    method: 'delete',
                    url: `users/${userId}`
                }).then(res => {
                    if (res.data.meta.status !== 200) {
                        this.$message.error("删除失败请重试")
                    } else {
                        this.$message.success("删除成功")
                        this.init()
                    }
                })
            },
            //分配用户角色对话框，
            setRole(scope) {
                this.selectedRoleId = scope.role_name
                this.userRole = scope
                this.setRoleDialog = true
                $axios({
                    method: 'get',
                    url: 'roles',
                }).then(res => {
                    if (res.data.meta.status !== 200) {
                        this.$message.error("请求失败")
                    } else {
                        this.userRoleList = res.data.data
                    }
                })
            },
            //更新用户角色请求
            updateUserRole() {
                if (!this.selectedRoleId) {
                    this.$message.error("请给用户分配角色")
                } else {
                    $axios({
                        url: `users/${this.userRole.id}/role`,
                        method: 'put',
                        data: {
                            rid: this.selectedRoleId
                        }
                    }).then(res => {
                        if (res.data.meta.status !== 200) {
                            this.$message.error("更新角色失败")
                        } else {
                            this.$message.success("更新角色成功")
                            this.init();
                            this.setRoleDialog = false
                        }
                    })
                }
            }
        },
        created() {
            this.init()
        },
        computed: {
            is_load() {
                return this.$store.state.is_loading
            }
        }
    }
</script>

<style scoped>

</style>
